//
//  ClassListVC.swift
//  PayDemo
//
//  Created by MoneyLee on 2020/8/20.
//  Copyright © 2020 MoneyLee. All rights reserved.
//

import UIKit
//导入购物推车
import StoreKit

class ClassListVC: UITableViewController {
    
    //管理后台创建的商品ID
    let productId = "com.gorun.PayDemo.soup"
    
    var freeClass = [
        "vue进阶", "docker学习", "java学习", "iOS基础"
    ]
    //付费课程
    let vipClass = [
        "iOS进阶", "人工智能", "微服务构建"
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        //添加一个观察者 苹果把收银的任务委托给这个控制器
        SKPaymentQueue.default().add(self)
        if isPay() {
            showAll()
        }
    }
    
    
    @IBAction func reStateClick(_ sender: Any) {
        //恢复已经完成的交易 会像苹果服务器发送个请求 会再次调用 func paymentQueue(_ queue: SKPaymentQueue,函数
        SKPaymentQueue.default().restoreCompletedTransactions()
        print("恢复购买")
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return isPay() ? freeClass.count : freeClass.count + 1
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //用户点击购买课程按钮
        if indexPath.row == freeClass.count {
            //实现内购
            let pay = SKMutablePayment()
            //添加商品 可以添加多个
            pay.productIdentifier = productId
            //加购物车 + 排队买单
            SKPaymentQueue.default().add(pay)
        }
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "class", for: indexPath)
        cell.backgroundColor = .white
        if indexPath.row == freeClass.count {
            cell.textLabel?.text = "购买课程"
            cell.textLabel?.textColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
            cell.accessoryType = .disclosureIndicator
        } else {
            cell.textLabel?.textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
            cell.textLabel?.text = freeClass[indexPath.row]
            cell.accessoryType = .none
        }
        cell.textLabel?.numberOfLines = 0
        return cell
    }

}

//委托苹果支付
extension ClassListVC: SKPaymentTransactionObserver {
    
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        
        for transaction in transactions {
            //购买成功
            if transaction.transactionState == .purchased {
                print("购买成功")
                savePayed()
                showAll()
                //无论购买成功还是失败都需要执行下面方法 相当于将购物车回收
                SKPaymentQueue.default().finishTransaction(transaction)
            //购买失败
            } else if transaction.transactionState == .failed {
                print("购买失败: \(String(describing: transaction.error?.localizedDescription))")
                SKPaymentQueue.default().finishTransaction(transaction)
            //恢复购买
            } else if transaction.transactionState == .restored{
                savePayed()
                showAll()
                SKPaymentQueue.default().finishTransaction(transaction)
            }
        }
        
    }
    
    //已购买
    func showAll() {
        freeClass.append(contentsOf: vipClass)
        tableView.reloadData()
        navigationItem.setRightBarButton(nil, animated: true)
    }
    
    //是否支付
    func isPay() -> Bool {
        return UserDefaults.standard.bool(forKey: productId)
    }
    //保存购买状态到本机
    func savePayed() {
        UserDefaults.standard.setValue(true, forKey: productId)
    }
    
    
}
